#include "adalog/buffer/ReadBufferGuard.h"

namespace adalog
{
    ReadBufferGuard::ReadBufferGuard(std::shared_ptr<BufferHeader> buffer)
        : buffer_(std::move(buffer))
        , is_valid_(true)
    {
    }

    ReadBufferGuard::~ReadBufferGuard()
    {
        if (is_valid_)
        {
            buffer_->pin_count_--;
            buffer_.reset();
            is_valid_ = false;
        }
    }

    ReadBufferGuard::ReadBufferGuard(ReadBufferGuard&& that) noexcept
    {
        *this = std::move(that);
    }

    ReadBufferGuard& ReadBufferGuard::operator=(ReadBufferGuard&& that) noexcept
    {
        if (this != &that) 
        {
            buffer_ = std::move(that.buffer_);     
            is_valid_ = that.is_valid_;
            that.is_valid_ = false;
        }
        return *this;
    }

    size_t ReadBufferGuard::GetBufferId() const
    {
        if (!is_valid_)
            throw std::runtime_error("Trying to use a invalid ReadBufferGaurd");
        return buffer_->GetBufferId();
    }

    const char* ReadBufferGuard::GetDataBegin() const
    {
        if (!is_valid_) 
            throw std::runtime_error("Trying to use a invalid ReadBufferGaurd");
        return buffer_->GetDataBegin();
    }

    size_t ReadBufferGuard::ReadableSize() const
    {
        if (!is_valid_)
            throw std::runtime_error("Trying to use a invalid ReadBufferGaurd");
        return buffer_->ReadableSize();
    }


} // namespace adalog